// utils/request.js
import config from './config';

let isShowingLoginModal = false; // 防止重复弹窗

const request = (url, method, data = {}, header = {}) => {
  const token = uni.getStorageSync('access_token');

  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + url,
      method,
      data,
      header: {
        ...header,
        'Authorization': token ? `Bearer ${token}` : '',
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          // 401处理逻辑
          if (res.statusCode === 401 && !isShowingLoginModal) {
            isShowingLoginModal = true;
            uni.showModal({
              title: '登录过期',
              content: '登录状态已失效，请重新登录',
              confirmText: '去登录',
              showCancel: false,
              success: () => {
                uni.removeStorageSync('access_token');
                uni.reLaunch({ url: '/pages/index/login' });
              },
              complete: () => {
                isShowingLoginModal = false;
              }
            });
          } else {
            uni.showToast({ title: res.data?.message || '请求失败', icon: 'none' });
          }
          reject(res.data);
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络异常', icon: 'none' });
        reject(err);
      }
    });
  });
};

// 保持原有导出方式不变
export const { staticURL } = config;
export default {
  get: (url, data, header) => request(url, 'GET', data, header),
  post: (url, data, header) => request(url, 'POST', data, header),
  put: (url, data, header) => request(url, 'PUT', data, header),
  delete: (url, data, header) => request(url, 'DELETE', data, header)
};